package cn.tedu.luban.settle.main.service;

import cn.tedu.luban.account.api.AccountApi;
import cn.tedu.luban.account.protocol.param.AccountPayParam;
import cn.tedu.luban.order.protocol.dto.OrderMessageDTO;
import cn.tedu.luban.settle.main.converter.SettleConverter;
import cn.tedu.luban.settle.main.repository.SettleRepository;
import cn.tedu.luban.settle.protocol.param.SettleBillParam;
import com.tedu.inn.protocol.exception.BusinessException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SettleService {
    @Autowired
    private SettleRepository settleRepository;
    @Autowired
    private SettleConverter settleConverter;
    @Autowired
    private AccountApi accountApi;
    @Autowired
    private MessageService messageService;
    public void settle(OrderMessageDTO orderMessageDTO) throws BusinessException {
        log.info("接受到消息：{}",orderMessageDTO);
        String orderNo = orderMessageDTO.getOrderNo();
        Long total=settleRepository.countSettleBillByOrderNo(orderNo);
        log.info("查询到的账单数量：{}",total);
        if (total>0){
            throw new BusinessException("1999","已存在结账账单");
        }
        List<SettleBillParam> params=settleConverter.dto2params(orderMessageDTO);
        //写入表格
        settleRepository.batchSave(params);
        //远程模拟打款
        AccountPayParam paymentParam=new AccountPayParam();
        paymentParam.setUserId(orderMessageDTO.getUserId());
        paymentParam.setOrderNo(orderNo);
        paymentParam.setTotalAmount(params.get(0).getTotalAmount());
        accountApi.mockPayment(paymentParam);
        messageService.sendSettledMessage(orderNo);
    }
}
